const connection = require("../db/mysql")

const addService = async (todo) => {
  let result = "error"
  const sql = 'INSERT INTO todolist(title,completed) VALUES (?,?);';
  const sqlParams = [todo.title, 0];
  result = await new Promise((resolve, reject) => {
    connection.query(sql, sqlParams, (err, res) => {
      if(res.affectedRows > 0){
        resolve("success")
        return
      }
    })
  })
  return result
}

const delService = (todoId) => {
  let result = "error"
  const sql = 'DELETE FROM todolist WHERE id = ?;';
  const sqlParams = [todoId];
  result = new Promise((resolve, reject) => {
    connection.query(sql, sqlParams, (err, res) => {
      if(res.affectedRows > 0) {
        resolve("success")
        return
      }
    })
  })
  return result
}

const delAllService = async () => {
  let result = "error"
  const sql = "DELETE FROM todolist;"
  result = await new Promise((resolve,reject) => {
    connection.query(sql, (err, res) => {
      if (err) {
        reject()
        return
      }
      resolve("success")
    })
  })
  return result
}

const listService = async () => {
  let result = "error"
  const sql = "SELECT * FROM todolist;"
  result = await new Promise((resolve,reject) => {
    connection.query(sql, (err, res) => {
      if (err) {
        reject()
        return
      }
      resolve(JSON.parse(JSON.stringify(res)))
    })
  })
  return result
}

const updateService = async (todo) => {
  let result = "error"
  console.log(todo);
  const sql = 'UPDATE todolist SET title = ?, completed = ?, updated = now() WHERE id = ?;';
  const sqlParams = [todo.title, todo.completed, todo.id];
  result = await new Promise((resolve, reject) => {
    const a = connection.query(sql, sqlParams, (err, res) => {
      if(res.affectedRows > 0){
        resolve("success")
        return
      }
    })
  })
  return result
}


module.exports = {
  addService,
  listService,
  delService,
  updateService,
  delAllService
}